<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";

// 状态管理
const videoRef = ref<HTMLVideoElement | null>(null);
const pipEnabled = ref(false);
const statusMessage = ref("准备就绪");
const loadingProgress = ref(0);
const isLoading = ref(false);
const currentTask = ref<Task | null>(null);
const showTaskInPip = ref(false);
const countdown = ref(0);
const countdownInterval = ref<number | null>(null);
const pipWindow = ref<PictureInPictureWindow | null>(null);

// WebSocket 连接
let ws: WebSocket | null = null;

// 任务类型定义
interface Task {
  id: string;
  title: string;
  description: string;
  countdown: number;
  type: "notification" | "quiz" | "reminder";
  options?: string[];
  correctAnswer?: number;
}

// 模拟任务数据
const demoTasks: Task[] = [
  {
    id: "task1",
    title: "学习提醒",
    description: "请完成视频学习后的练习题",
    countdown: 60,
    type: "notification"
  },
  {
    id: "task2",
    title: "测验问题",
    description: "以下哪一项是画中画模式的主要优势？",
    countdown: 30,
    type: "quiz",
    options: [
      "降低设备耗电量",
      "允许用户同时进行多任务处理",
      "提升视频画质",
      "减少网络带宽使用"
    ],
    correctAnswer: 1
  },
  {
    id: "task3",
    title: "完成提示",
    description: "恭喜！您已完成本节学习内容",
    countdown: 15,
    type: "reminder"
  }
];

// 生命周期钩子
onMounted(() => {
  setupEventListeners();
  
  // 模拟WebSocket连接
  initializeWebSocket();
});

onUnmounted(() => {
  cleanupEventListeners();
  cleanupWebSocket();
  stopCountdown();
  exitPictureInPicture();
});

// 初始化WebSocket连接
const initializeWebSocket = () => {
  // 真实环境中应该连接到实际的WebSocket服务器
  // ws = new WebSocket("wss://example.com/tasks");
  
  // 此处使用模拟数据替代WebSocket
  statusMessage.value = "WebSocket连接模拟成功";
  console.log("WebSocket连接已模拟建立");
};

// 清理WebSocket连接
const cleanupWebSocket = () => {
  if (ws) {
    ws.close();
    ws = null;
  }
};

// 设置事件监听器
const setupEventListeners = () => {
  if (videoRef.value) {
    videoRef.value.addEventListener("enterpictureinpicture", handleEnterPictureInPicture);
    videoRef.value.addEventListener("leavepictureinpicture", handleLeavePictureInPicture);
  }
};

// 清理事件监听器
const cleanupEventListeners = () => {
  if (videoRef.value) {
    videoRef.value.removeEventListener("enterpictureinpicture", handleEnterPictureInPicture);
    videoRef.value.removeEventListener("leavepictureinpicture", handleLeavePictureInPicture);
  }
};

// 处理进入画中画模式
const handleEnterPictureInPicture = (event: Event) => {
  pipEnabled.value = true;
  statusMessage.value = "已进入画中画模式";
  
  const pipWindowEvent = event as unknown as { pictureInPictureWindow: PictureInPictureWindow };
  pipWindow.value = pipWindowEvent.pictureInPictureWindow;
  
  // 添加画中画窗口大小变化的监听
  if (pipWindow.value) {
    pipWindow.value.addEventListener("resize", updatePipOverlay);
  }
  
  // 延迟一点时间再初始化叠加层，确保PiP窗口已完全创建
  setTimeout(() => {
    initializeTaskOverlay();
  }, 500);
};

// 处理离开画中画模式
const handleLeavePictureInPicture = () => {
  pipEnabled.value = false;
  showTaskInPip.value = false;
  statusMessage.value = "已退出画中画模式";
  
  if (pipWindow.value) {
    pipWindow.value.removeEventListener("resize", updatePipOverlay);
    pipWindow.value = null;
  }
};

// 更新PiP叠加层
const updatePipOverlay = () => {
  // 窗口大小发生变化时更新叠加层
  if (pipEnabled.value && currentTask.value) {
    initializeTaskOverlay();
  }
};

// 进入画中画模式
const enterPictureInPicture = async () => {
  if (!videoRef.value) return;
  
  // 检查浏览器是否支持画中画
  if (!document.pictureInPictureEnabled) {
    statusMessage.value = "您的浏览器不支持画中画模式";
    return;
  }
  
  try {
    // 确保视频已加载
    if (videoRef.value.readyState === 0) {
      await new Promise<void>((resolve) => {
        videoRef.value!.addEventListener("loadedmetadata", () => resolve(), { once: true });
      });
    }
    
    // 确保视频处于播放状态
    if (videoRef.value.paused) {
      await videoRef.value.play();
    }
    
    // 请求画中画模式
    await videoRef.value.requestPictureInPicture();
    statusMessage.value = "已请求画中画模式";
  } catch (error) {
    console.error("无法进入画中画模式:", error);
    statusMessage.value = "无法进入画中画模式，请确保视频已开始播放";
  }
};

// 退出画中画模式
const exitPictureInPicture = async () => {
  if (!document.pictureInPictureElement) return;
  
  try {
    await document.exitPictureInPicture();
    statusMessage.value = "已退出画中画模式";
  } catch (error) {
    console.error("无法退出画中画模式:", error);
    statusMessage.value = "无法退出画中画模式";
  }
};

// 初始化任务叠加层
const initializeTaskOverlay = () => {
  if (!pipEnabled.value || !document.pictureInPictureElement) return;
  
  // 模拟任务推送
  // 在实际环境中，这将由WebSocket的onmessage事件处理
  showRandomTask();
};

// 显示随机任务（模拟WebSocket推送）
const showRandomTask = () => {
  const randomIndex = Math.floor(Math.random() * demoTasks.length);
  const task = demoTasks[randomIndex];
  
  displayTask(task);
};

// 显示任务
const displayTask = (task: Task) => {
  currentTask.value = task;
  showTaskInPip.value = true;
  
  // 设置倒计时
  countdown.value = task.countdown;
  startCountdown();
  
  // 通知主界面已接收到新任务
  console.log("接收到新任务:", task);
};

// 开始倒计时
const startCountdown = () => {
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value);
  }
  
  countdownInterval.value = window.setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      // 倒计时结束，清除任务
      clearTask();
    }
  }, 1000);
};

// 停止倒计时
const stopCountdown = () => {
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value);
    countdownInterval.value = null;
  }
};

// 清除当前任务
const clearTask = () => {
  stopCountdown();
  showTaskInPip.value = false;
  currentTask.value = null;
  
  // 模拟一段时间后推送新任务
  setTimeout(() => {
    if (pipEnabled.value) {
      showRandomTask();
    }
  }, 5000);
};

// 回答测验问题
const answerQuiz = (optionIndex: number) => {
  if (!currentTask.value || currentTask.value.type !== "quiz") return;
  
  const correct = optionIndex === currentTask.value.correctAnswer;
  
  // 处理答题结果
  statusMessage.value = correct ? "答题正确！" : "答题错误，请再试一次";
  
  // 延迟后清除当前任务
  setTimeout(() => {
    clearTask();
  }, 2000);
  
  // 将结果同步到主界面
  console.log("测验回答:", { 
    taskId: currentTask.value.id, 
    answer: optionIndex, 
    correct
  });
};

// 模拟推送新任务
const pushNewTask = () => {
  if (!pipEnabled.value) {
    statusMessage.value = "请先进入画中画模式";
    return;
  }
  
  showRandomTask();
};
</script>

<template>
  <div class="pip-learning-assistant">
    <h2>沉浸式多任务学习助手</h2>
    
    <!-- 状态提示 -->
    <div class="status-message">{{ statusMessage }}</div>
    
    <!-- 视频区域 -->
    <div class="video-container">
      <video 
        ref="videoRef"
        controls
        crossorigin="anonymous"
        class="main-video"
        loop
        src="../assets/sea.mp4"
      ></video>
      
      <!-- 控制按钮 -->
      <div class="button-group">
        <button @click="enterPictureInPicture" :disabled="pipEnabled">
          进入画中画模式
        </button>
        <button @click="exitPictureInPicture" :disabled="!pipEnabled">
          退出画中画模式
        </button>
        <button @click="pushNewTask" :disabled="!pipEnabled">
          推送测试任务
        </button>
      </div>
    </div>
    
    <!-- 加载指示器 -->
    <div v-if="isLoading" class="loading-indicator">
      <div class="spinner"></div>
      <div>{{ statusMessage }}</div>
      <div v-if="loadingProgress > 0" class="progress-container">
        <div class="progress-bar" :style="{ width: loadingProgress + '%' }"></div>
        <div class="progress-text">{{ loadingProgress }}%</div>
      </div>
    </div>
    
    <!-- 当前任务信息 -->
    <div v-if="currentTask" class="current-task">
      <h3>当前任务</h3>
      <div class="task-card">
        <div class="task-header">
          <h4>{{ currentTask.title }}</h4>
          <span class="task-countdown">{{ countdown }}秒</span>
        </div>
        <div class="task-body">
          <p>{{ currentTask.description }}</p>
          
          <!-- 测验选项 -->
          <div v-if="currentTask.type === 'quiz'" class="quiz-options">
            <button 
              v-for="(option, index) in currentTask.options" 
              :key="index"
              @click="answerQuiz(index)"
              class="quiz-option"
            >
              {{ option }}
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 任务历史记录 -->
    <div class="task-history">
      <h3>任务历史</h3>
      <div class="history-list">
        <div v-for="(task, index) in demoTasks" :key="`history-${index}`" class="history-item">
          <div class="history-task-title">{{ task.title }}</div>
          <div class="history-task-description">{{ task.description }}</div>
        </div>
      </div>
    </div>
    
    <!-- 说明信息 -->
    <div class="instructions">
      <h3>使用说明</h3>
      <ul>
        <li>点击"进入画中画模式"按钮，视频将浮动显示在其他窗口之上</li>
        <li>系统将自动在视频上叠加学习任务、倒计时和测验题目</li>
        <li>您可以在画中画窗口中直接回答问题和完成任务</li>
        <li>所有交互结果会自动同步到主界面</li>
        <li>画中画模式让您可以在主屏幕执行其他任务（如编程、写作）的同时，不错过重要的学习内容</li>
      </ul>
    </div>
  </div>
</template>

<style lang="less" scoped>
.pip-learning-assistant {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;

  h2 {
    color: #333;
    margin-bottom: 20px;
    text-align: center;
  }
  
  .status-message {
    margin: 10px 0;
    padding: 10px;
    background-color: #f8f9fa;
    border-radius: 4px;
    text-align: center;
    transition: all 0.3s ease;
  }
  
  .video-container {
    margin: 20px 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .main-video {
      width: 100%;
      max-width: 800px;
      border-radius: 8px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      background-color: #000;
    }
  }
  
  .button-group {
    margin-top: 15px;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    justify-content: center;
  }
  
  button {
    padding: 8px 16px;
    border: 1px solid #ddd;
    background-color: #f0f0f0;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s ease;
    
    &:hover:not(:disabled) {
      background-color: #e6f7ff;
      border-color: #1890ff;
      color: #1890ff;
    }
    
    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }
  }
  
  .loading-indicator {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 20px 0;
    
    .spinner {
      border: 4px solid rgba(0, 0, 0, 0.1);
      border-radius: 50%;
      width: 40px;
      height: 40px;
      border-top: 4px solid #4caf50;
      animation: spin 1s linear infinite;
      margin-bottom: 10px;
    }
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  
  .progress-container {
    width: 80%;
    height: 20px;
    background-color: #f0f0f0;
    border-radius: 10px;
    margin: 10px auto;
    position: relative;
    overflow: hidden;
    
    .progress-bar {
      height: 100%;
      background-color: #4caf50;
      border-radius: 10px;
      transition: width 0.3s ease;
    }
    
    .progress-text {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      text-align: center;
      line-height: 20px;
      color: #fff;
      text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
      font-weight: bold;
    }
  }
  
  .current-task {
    margin: 20px 0;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 8px;
    border-left: 4px solid #1890ff;
    
    h3 {
      color: #444;
      margin: 0 0 15px;
    }
    
    .task-card {
      background-color: #fff;
      border-radius: 6px;
      padding: 15px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      
      .task-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        border-bottom: 1px solid #eee;
        padding-bottom: 10px;
        
        h4 {
          margin: 0;
          color: #333;
        }
        
        .task-countdown {
          background-color: #f0f0f0;
          border-radius: 12px;
          padding: 2px 8px;
          font-size: 14px;
          color: #666;
          font-weight: bold;
        }
      }
      
      .task-body {
        p {
          margin-top: 0;
          color: #555;
        }
        
        .quiz-options {
          display: flex;
          flex-direction: column;
          gap: 8px;
          margin-top: 15px;
          
          .quiz-option {
            text-align: left;
            padding: 10px;
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 4px;
            transition: all 0.2s ease;
            
            &:hover {
              background-color: #e6f7ff;
              border-color: #1890ff;
            }
          }
        }
      }
    }
  }
  
  .task-history {
    margin: 20px 0;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 8px;
    
    h3 {
      color: #444;
      margin: 0 0 15px;
    }
    
    .history-list {
      max-height: 300px;
      overflow-y: auto;
      
      .history-item {
        padding: 10px;
        margin-bottom: 8px;
        background-color: #fff;
        border-radius: 4px;
        border-left: 3px solid #ccc;
        
        .history-task-title {
          font-weight: bold;
          color: #333;
          margin-bottom: 5px;
        }
        
        .history-task-description {
          color: #666;
          font-size: 14px;
        }
      }
    }
  }
  
  .instructions {
    margin-top: 30px;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 4px;
    
    h3 {
      color: #444;
      margin: 0 0 15px;
    }
    
    ul {
      padding-left: 20px;
      
      li {
        margin-bottom: 8px;
        color: #555;
      }
    }
  }
  
  // 画中画内容叠加样式
  .pip-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.3);
    color: white;
    padding: 10px;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    pointer-events: none;
    
    .pip-task {
      background-color: rgba(0, 0, 0, 0.7);
      border-radius: 4px;
      padding: 10px;
      margin-bottom: 10px;
      max-width: 80%;
      
      .pip-task-title {
        font-weight: bold;
        margin-bottom: 5px;
      }
      
      .pip-countdown {
        background-color: rgba(255, 255, 255, 0.2);
        border-radius: 10px;
        padding: 2px 8px;
        font-size: 12px;
        display: inline-block;
        margin-top: 5px;
      }
    }
  }
  
  // 适配移动设备
  @media (max-width: 768px) {
    .video-container {
      margin: 15px 0;
    }
    
    .button-group {
      flex-direction: column;
      align-items: center;
    }
    
    button {
      width: 100%;
    }
  }
}
</style>
